from sqlalchemy import asc
from model.user_point import UserPoint
from model.point_code import PointCode


class UserPointService:
    def __init__(self, session):
        self.session = session

    def add_points(self, points):
        self.session.add(points)

    def get_point_dict(self):
        q = self.session.query(PointCode)
        result = q.order_by(asc(PointCode.points_code)).all()
        record = []
        if result:
            for row in result:
                record.append({
                    'points_code': row.points_code,
                    'points_name': row.points_name,
                    'points': row.points,
                    'points_remark': row.points_remark
                })
            return record
        else:
            return None

    ##获得人员积分
    def get_points_by_user_id(self, user_id):
        result = []
        total_point = 0
        q = self.session.query(UserPoint,
                               UserPoint.points_id,
                               UserPoint.user_id,
                               UserPoint.points_code,
                               UserPoint.create_time,
                               PointCode.points,
                               PointCode.points_name
                               ) \
            .join(PointCode,
                  UserPoint.points_code
                  == PointCode.points_code) \
            .filter(UserPoint.user_id == user_id).all()
        if q:
            for dd in q:
                total_point = +dd.points
                result.append({"user_id": dd.user_id,
                               "points_id": dd.points_id,
                               "points_code": dd.points_code,
                               "points_name": dd.points_name,
                               "points": dd.points,
                               "create_time": dd.create_time.strftime('%Y-%m-%d %H:%M:%S')
                               })

            return {'result': result,
                    'total_point': total_point}
        else:
            return None


if __name__ == '__main__':
    # from utils.work_db import Session
    # session = Session()
    # service = UserPointsService(session)
    # ss = service.get_points_by_user_id(21)
    # print(ss)
    # session.close()
    pass
